package _022_1_29

func checkWordSizeIsOverflow(allWordSize int, wordNum int, maxWidth int) bool {
	if allWordSize+wordNum > maxWidth {
		return true
	}
	return false
}

func distributeSpaceNum(spaceSize int, wordSize int) []int {
	spaces := make([]int, 0)
	avgSpaceMaxSize := 0

	if wordSize == 1 {
		avgSpaceMaxSize = spaceSize
	} else {
		avgSpaceMaxSize = spaceSize / (wordSize - 1)
	}

	i := 0
	for i = spaceSize; i >= avgSpaceMaxSize; {
		spaces = append(spaces, avgSpaceMaxSize)
		i -= avgSpaceMaxSize
	}
	if i != 0 {
		spaces = append(spaces, i)
	}
	return spaces
}

func createLineStr(words []string, beg int, end int, allWordsSize int, maxWidth int) string {
	spaces := distributeSpaceNum(maxWidth-allWordsSize, end-beg+1)
	resultStr := ""

	for i := 0; i < len(spaces); i++ {
		resultStr += words[beg+i]
		for j := 0; j < spaces[i]; j++ {
			resultStr += " "
		}
	}
	resultStr += words[end]
	return resultStr
}

func fullJustify(words []string, maxWidth int) []string {
	beginId := 0
	result := make([]string, 0)
	for true {
		tempSize := 0
		oldBegId := beginId
		for ; beginId < len(words); beginId++ {
			tempSize += len(words[beginId])
			if checkWordSizeIsOverflow(tempSize, beginId-oldBegId+1, maxWidth) {
				tempSize -= len(words[beginId])
				beginId--
				break
			}
		}

		str := createLineStr(words, oldBegId, beginId, beginId-oldBegId+1, maxWidth)
		result = append(result, str)
	}
	return result
}
